<?php

namespace app\modules\index\services;

use app\common\services\BaseService;
use app\config\Constants;
use app\models\Goods;
use app\utils\UserUtil;
use yii\helpers\ArrayHelper;

class GoodsService extends BaseService{

    private const SELECT = ['goods_id','merchant_id','cat_id','goods_name','goods_desc','thumbnail','weight','price','count'];

    /**
     * 搜索
     * @param $merchant_id
     * @param $goods_name
     * @return array
     */
    public static function search($merchant_id,$goods_name){
        $query = Goods::find()
            ->asArray(true)
            ->orderBy(['sort'=>SORT_ASC])
            ->select(self::SELECT)
            ->andWhere(['is_sale'=>2]);

        if(!empty($merchant_id)){
            $query->andWhere(['merchant_id'=>$merchant_id]);
        }
        if(!empty($goods_name)){
            $query->andWhere(['like','goods_name',$goods_name]);
        }

        $data = $query->all();
        //对普通用户和游客屏蔽货行价格
        if(!empty($merchant_id) && MerchantService::getInfoById($merchant_id)['customer_type'] == Constants::CUSTOMER_TYPE_STORE){
            $user = UserUtil::getModuleUserIdentity("index");
            if(!$user || !$user->userInfoStore || $user->userInfoStore->is_verify != Constants::VERIFY_SUCCESS){
                foreach($data as $k=>$v){
                    $data[$k]['price'] = 0;
                }
            }
        }

        //属性和库存
        foreach ($data as $k=>$v){
            $attr_item = GoodsAttributeService::search(null,$v['goods_id'],null);
            if(empty($attr_item)){
                continue;
            }
            $attr_item = ArrayHelper::index($attr_item,null,"attr_id");
            foreach($attr_item as $kk=>$vv){
                $attr = AttributeService::getInfoById($kk);
                if(empty($attr)){
                    continue;
                }
                $data[$k]['attr_item'][] = ['attr_id'=>$attr->attr_id,'attr_name'=>$attr->attr_name,'item'=>$attr_item[$kk]];
            }
        }

        return $data;
    }

    /**
     * 获取信息
     * @param $merchant_id
     * @param $goods_id
     * @return Goods
     */
    public static function getInfoById($merchant_id,$goods_id){
        return Goods::findOne(['merchant_id'=>$merchant_id,'goods_id'=>$goods_id,'is_sale'=>2]);
    }
}